from helpers import updateInfo
from helpers import CompHelp
import datetime
import pickle
import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class CompetitionListPage(webapp.RequestHandler):
    """ List competitions (arena and portfolio) class """
    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
        
        try:
            compType=int(self.request.get('type'))
        except:
            self.response.out.write("Wrong type given")
            return
            
        if compType==0:
            categoryName="Portfolio Competitions %s" % updateInfo.createToolTip("portfolio competition")
        elif compType==1:
            categoryName="Arena Competitions %s" % updateInfo.createToolTip("arena competition")
        else:
            self.response.out.write("Wrong type given")
            return
            
        q_1 = db.GqlQuery("SELECT * FROM Competition WHERE members = :1 AND type= :2" , current_user.key(),compType)
        q_1=q_1.fetch(1000)
    
        competition_table_Text="\ndata.addRows(%d);\n" % (len(q_1))
        
        # We are using the same code for the two competition tables without a function currently
        # That is because future implemetation will change the second table to feature more details about competitions
        
        i=0
        for competition in q_1:
                membersCount=len(competition.members)
                current_bank=competition.compamount*membersCount
                competition.title=competition.title.replace("'","\\'")
                competition_table_Text+="data.setCell(%d, 0, '%s', '<a href=\"/Competition?id=%s&PKey=%s\">%s</a>',{style: 'font-weight:bold;'});\n" % (i,competition.title,competition.key(), competition.password,competition.title)
                competition_table_Text+="data.setCell(%d, 1, %d,'%d',{style: 'text-align:center;'});\n" % (i,membersCount,membersCount)
                competition_table_Text+="data.setCell(%d, 2, %d, '$%d',{style: 'text-align:center;'});\n" % (i,competition.compamount,competition.compamount)
                competition_table_Text+="data.setCell(%d, 3, %d, '$%d',{style: 'text-align:center;'});\n" % (i,current_bank,current_bank)
                competition_table_Text+="data.setCell(%d, 4, '%s','%s',{style: 'text-align:center;'});\n" % (i,competition.startdate,competition.startdate)
                competition_table_Text+="data.setCell(%d, 5, '%s','%s',{style: 'text-align:center;'});\n" % (i,competition.enddate,competition.enddate)
                i=i+1
        
        q_1 = db.GqlQuery("SELECT * FROM Competition WHERE public=True AND type= :1 ORDER BY isAd DESC",compType)
        q_1=q_1.fetch(1000)
        
        competition_pub_table_Text="\ndata2.addRows(%d);\n" % (len(q_1))
        
        i=0
        for competition in q_1:
                if competition.isAd:
                    cssStyle="background-color:#FFE400;font-weight:bold;"
                    # Show competition amount as "Free"
                    freeText="Free"
                else:
                    cssStyle=""
                    # Show competition amount
                    freeText="$%d" % competition.compamount
                membersCount=len(competition.members)
                if competition.isAd:
                    current_bank=competition.advamount
                else:
                    current_bank=competition.compamount*membersCount
                
                competition.title=competition.title.replace("'","\\'")
                competition_pub_table_Text+="data2.setCell(%d, 0, '%s', '<a href=\"/Competition?id=%s&PKey=%s\">%s</a>',{style: 'font-weight:bold;%s'});\n" % (i,competition.title,competition.key(), competition.password,competition.title, cssStyle)
                competition_pub_table_Text+="data2.setCell(%d, 1, %d,'%d',{style: 'text-align:center;%s'});\n" % (i,membersCount,membersCount, cssStyle)
                competition_pub_table_Text+="data2.setCell(%d, 2, %d, '%s',{style: 'text-align:center;%s'});\n" % (i,competition.compamount,freeText, cssStyle)
                competition_pub_table_Text+="data2.setCell(%d, 3, %d, '$%d',{style: 'text-align:center;%s'});\n" % (i,current_bank,current_bank, cssStyle)
                competition_pub_table_Text+="data2.setCell(%d, 4, '%s','%s',{style: 'text-align:center;%s'});\n" % (i,competition.startdate,competition.startdate, cssStyle)
                competition_pub_table_Text+="data2.setCell(%d, 5, '%s','%s',{style: 'text-align:center;%s'});\n" % (i,competition.enddate,competition.enddate, cssStyle)
                i=i+1
                
        template_values = {
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            'categoryName' : categoryName,
            'competition_table_Text':competition_table_Text,
            'competition_pub_table_Text':competition_pub_table_Text,
            'setHead' : 1,
            'maincontent' : 'account_main.html',
            'headContent' : 'complist_head.html',
            'account_main_content' : 'complist_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))
        
        
class CompetitionPage(webapp.RequestHandler):
    """ Competition (arena and portfolio) page class """
    def get(self):
        user=users.get_current_user()
        
        # Make sure user is logged in, if not redirect to login page
        if not user:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        # Load user info from database
        # If user is using app for first time (=his info in not in TrendUsers table)
        # then initialize his info
        current_user=updateInfo.getCurrentUser(user)
        
        compkey=self.request.get('id')
        try:
            competition=updateInfo.db.get(db.Key(compkey))
        except:
            self.response.out.write("Wrong ID provided")
            return
        
        # Wrong password
        if not isinstance(competition,updateInfo.Competition) or competition.password!=self.request.get('PKey'):
            self.response.out.write("Wrong ID provided")
            return -1
        
        # Retrieve competition data from datastore
        compType=competition.type
        compInfoStatus=competition.status
        compInfoPrice=competition.compamount
        
        if competition.isAd:
            compInfoBank=competition.advamount
        else:
            compInfoBank=competition.compamount*len(competition.members)
            
        compInfoStartDate=competition.startdate.strftime("%Y-%m-%d")
        compInfoDatesToGo=competition.enddate-datetime.date.today()
        compInfoTitle=competition.title
        
        # Start building competition page
        if compInfoDatesToGo.days==1:
            compInfoDatesToGo="Tomorrow"
        else:
            compInfoDatesToGo="In %d days" % compInfoDatesToGo.days
        
        # Competition hasn't started yet
        welcomeMsg1=""
        welcomeMsg2=""
        compInfoUserRanking=1
        showArenaAction=1
        
        if compInfoStatus==0:
            compInfoMsg=1
            compInfoOpenToGo=competition.startdate-datetime.date.today()
            if compInfoOpenToGo.days==1:
                compInfoOpenToGo="Tomorrow"
            else:    
                compInfoOpenToGo="in %d days" % compInfoOpenToGo.days
                
            welcomeMsg1="Competition will open %s."  % compInfoOpenToGo
            
            if current_user.key() in competition.members:
                welcomeMsg2="You have already enrolled to this competition."
            
            elif self.request.get('join')=="1":
                    res=CompHelp.joinCompetition(current_user,competition, compType, self.request.get('beton'))
                    if res==1:
                        welcomeMsg2="Thank you for joining"
                    elif res==-1:
                        welcomeMsg2="You do not have enough money in your bank account"
                    else:
                        welcomeMsg2="Error occured while trying to join competition"
            else:
                if current_user.bankamount<competition.compamount:
                    welcomeMsg2="You do not have enough money in your bank account to join this compettion. Try selling some stocks first"
                elif compType==0:
                    welcomeMsg2="<BR />By joining this competition you must invest $%d<BR /><a href=\"/Competition?id=%s&PKey=%s&join=1\">Click to join competition</a>" % (competition.compamount,compkey, self.request.get('PKey'))
                elif compType==1:
                    welcomeMsg2="<BR />By joining this arena competition you must invest $%d<BR />" % (competition.compamount)
                    
        # Competition is running
        elif compInfoStatus==1:
            showArenaAction=0
            compInfoMsg=0
        
        # Competition ended (with participants)
        elif compInfoStatus==2:
            showArenaAction=0
            compInfoMsg=1
            welcomeMsg1="Competition is over and closed. Results are published here.<BR />Please note that this page will no longer be available two weeks after the competition end date"
            compInfoDatesToGo="Ended"
        
        # Competition ended (no participants)
        elif compInfoStatus==3:
            showArenaAction=0
            compInfoMsg=1
            welcomeMsg1="No participants joined this competition."
            compInfoDatesToGo="Ended"
        
        if current_user.key() in competition.members:
            countRank=True
            compInfoUserRanking=1
        else:
            countRank=False
            compInfoUserRanking="-"
    
        # Build competition table
        zipped=competition.members
        zippedLen=len(zipped)
        table_users_Text=""
        column_users_Text=""
        
        if countRank:
            userListIndex=competition.members.index(current_user.key())
            if compType==0:
                # Current User score (used for ranking calc)
                userpercentCng=competition.membersAmount[userListIndex]
            if compType==1:
                userChoice=competition.membersChoice[userListIndex]
            
        entities_Text=""
        i=0
        if compType==0:
            table_users_Text="\ndata.addRows(%d);\n" % (zippedLen)
            column_users_Text="\ndata2.addRows(%d);\n" % (zippedLen)
            for p in competition.members:
                    current_member=db.get(p)
                    percentCng=competition.membersAmount[i]
                    
                    printPercentage, fontColor, changeSign= updateInfo.getPerInfo(percentCng)
                    
                    if percentCng<1:
                        printPercentage=printPercentage*-1
                    if countRank and percentCng>userpercentCng:
                        compInfoUserRanking=compInfoUserRanking+1
                        
                    table_users_Text+="data.setCell(%d, 0, '%s', '%s',{style: 'font-weight:bold;'});\n" % (i,current_member.tuser.nickname().capitalize(),current_member.tuser.nickname().capitalize())
                    table_users_Text+="data.setCell(%d, 1, %.2f,'(%s%.2f)',{style: 'color:%s;'});\n" % (i,percentCng, changeSign, printPercentage, fontColor)
                    column_users_Text+="data2.setValue(%d, 0, '%s');\n" % (i,current_member.tuser.nickname().capitalize())
                    column_users_Text+="data2.setValue(%d, 1, %.2f);\n" % (i,printPercentage)
                    i+=1
            
        # Build entities list
        if compType==1:
            keywordsList=pickle.loads(competition.arenaKeywords)
            entities_Text="\ndata3.addRows(%d);\n" % (len(keywordsList))
            column_users_Text="\ndata2.addRows(%d);\n" % (len(keywordsList))
            
            memberOfKeyword=[]
            memberOfKeywordOther=[]
            showNumOfMem=[]
            isMemberOfComp=[]
            for i in range (0,len(keywordsList)):
                memberOfKeyword.append("")
                memberOfKeywordOther.append("")
                isMemberOfComp.append(0)
                showNumOfMem.append(0)
              
            # Build entities list  
            for currUser in competition.members:
                    current_member=db.get(currUser)
                    currentIndex=competition.membersChoice[competition.members.index(current_member.key())]
                    if showNumOfMem[currentIndex]<updateInfo.ArenaDisplayNumMembers:
                        memberOfKeyword[currentIndex]+="%s<BR /> " % (current_member.tuser.nickname().capitalize())
                        showNumOfMem[currentIndex]+=1
                        
                    else:
                        if current_member.key()==current_user.key():
                            isMemberOfComp[currentIndex]=1
                            print"a"
                        memberOfKeywordOther[currentIndex]="(and %d more others)" % (showNumOfMem[currentIndex])
            # Append user bet position
            for i in range (0,len(keywordsList)):
                if isMemberOfComp[i]==1:
                    memberOfKeywordOther[i]+="<BR /><b>Your bet!</b>"
                
            i=0
            for currentKeywords in keywordsList:
                displayKeywords=""
                displayKeywordsGraph=""
                for keyword in currentKeywords:
                    displayStock=db.get(keyword)
                    #if displayStock.isProfile:
                    displayKeywords+='<a href="/trendProfile?TKey=%s" style="color:#000000">%s</a><BR />' % (str(displayStock.key()),displayStock.stockname)
                    #else:
                        #displayKeywords+="%s<BR />" % (displayStock.stockname)
    
                    displayKeywordsGraph+="%s," % (displayStock.stockname)
                # Remove last <BR />
                if len(displayKeywords)>0:
                    displayKeywords=displayKeywords[0:len(displayKeywords)-6]
                
                percentCng=competition.compKeywordsAmount[i]
                    
                printPercentage, fontColor, changeSign= updateInfo.getPerInfo(percentCng)
                    
                if percentCng<1:
                    printPercentage=printPercentage*-1
                entities_Text+="data3.setCell(%d, 0, '%s');\n" % (i, displayKeywords)
                if showArenaAction==0:
                    entities_Text+="data3.setCell(%d, 1, %.2f,'(%s%.2f)',{style: 'color:%s;'});\n" % (i, percentCng, changeSign, printPercentage, fontColor)
                elif compInfoStatus==0 and not countRank:
                    entities_Text+="data3.setCell(%d, 1, '<b><a href=\"/Competition?id=%s&PKey=%s&join=1&beton=%d\">Bet Me!</a></b>');\n" % (i,compkey, self.request.get('PKey'),i)
                elif compInfoStatus==0 and countRank:
                    if userChoice==i:
                        betText='<b>Your Bet!</b>'
                    else:
                        betText=''
                    entities_Text+="data3.setCell(%d, 1, '%s');\n" % (i,betText)
                
                if memberOfKeywordOther[i]!="":
                    keywordsMembersText="%s %s" % (memberOfKeyword[i], memberOfKeywordOther[i])
                else:
                    keywordsMembersText=memberOfKeyword[i]
                entities_Text+="data3.setCell(%d, 2, '%s');\n" % (i,keywordsMembersText)
                column_users_Text+="data2.setCell(%d, 0, '%s');\n" % (i, displayKeywordsGraph)
                column_users_Text+="data2.setCell(%d, 1, %.2f);\n" % (i, printPercentage)
                i+=1
                
        commentsList=competition.comment_set.order('-created_date').fetch(1000)
        template_values = {
            'table_users_Text': table_users_Text,
            'column_users_Text': column_users_Text,
            'entities_Text': entities_Text,
            'current_user_totalamount': current_user.totalamount,
            'current_user_bankamount': current_user.bankamount,
            'current_user_investamount': current_user.totalamount-current_user.bankamount,
            'logusername' : user.nickname().capitalize(),
            'loginurl' : users.create_logout_url("/"),
            'logintext' : 'Sign Out',
            'categoryName' : 'Competition Arena - ' + compInfoTitle,
            'showArenaAction': showArenaAction,
            'compType' : compType,
            'compInfoPrice':compInfoPrice,
            'compInfoBank':compInfoBank,
            'compInfoStartDate' : compInfoStartDate,
            'compInfoDatesToGo': compInfoDatesToGo,
            'compInfoTitle' : compInfoTitle,
            'compInfoUserRanking' : compInfoUserRanking,
            'compInfoMsg':compInfoMsg,
            'welcomeMsg2': welcomeMsg2,
            'welcomeMsg1': welcomeMsg1,
            'compkey': compkey,
            'commentsListNum':len(commentsList),
            'commentsList' : competition.comment_set.order('-created_date'),
            'setHead' : 1,
            'maincontent' : 'account_main.html',
            'headContent' : 'comp_head.html',
            'account_main_content' : 'comp_main.html'
            
        }
        path = os.path.join(os.path.dirname(__file__), updateInfo.controllersIndexPath)
        self.response.out.write(template.render(path, template_values))


application = webapp.WSGIApplication(
                                     [('/Competition', CompetitionPage),
                                     ('/ListCompetitions', CompetitionListPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
